package com.fan.springboot.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fan.springboot.service.FileStore;
import com.fan.springboot.service.GlobalParams;

@RestController
@RequestMapping("/api")
public class UploadController {

	@Autowired
	private FileStore fileStore;

	// @Autowired
	// private PictureDao pictureDao;

	@RequestMapping(value = "/uploadPicture", method = RequestMethod.POST)
	public Object uploadPicture(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {

		// 先保存文件,取到返回值,再将记录插入数据库,记录在picture表里
		Map map = fileStore.uploadBy(file);
		String fileName = (String) map.get("fileName");
		String filePath = (String) map.get("filePath");
		String completePath = getFileBasePath(request) + filePath;

		// Picture picture = new Picture();
		// picture.setBelong(belong);
		// picture.setPictureName(fileName);
		// picture.setPicturePath(filePath);
		// picture.setPictureCompletePath(completePath);
		// pictureDao.save(picture);

		Map<String, Object> resultMap = new HashMap<>();

		resultMap.put("fileName", fileName);
		resultMap.put("filePath", filePath);
		resultMap.put("completePath", completePath);
		resultMap.put(GlobalParams.SUCCESS, true);

		return resultMap;

	}

	public String getFileBasePath(HttpServletRequest request) {
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
		return basePath;
	}

}
